package LessonWork;

public class PolySinglyList<E> extends SinglyList{
    private PolySinglyList<E> list;

    public PolySinglyList() {}
    public PolySinglyList(String polystr) {
        String[] split = polystr.replace("^", "").split("((?=\\+)|(?=\\-)|x)");
        int i = 0;
        if (split.length%2==1){
            this.insert(new TermX(Integer.parseInt(split[0]),0));
            i=1;
        }
        for (;i<split.length;i=i+2){
            this.insert(new TermX(Integer.parseInt(split[i]),Integer.parseInt(split[i+1])));
        }
    }

    public void Addall(PolySinglyList<TermX> polySinglyList){
        Node<TermX> p = this.head.next;
        Node<TermX> q = polySinglyList.head.next;
        Node<TermX> front = this.head;

        while (p.next!=null&&q!=null){
            if (p.data.xexp==q.data.xexp){
                if (p.data.coef+q.data.coef==0){
                    p=p.next;
                    q=q.next;
                    front.next=p;
                }else {
                    p.data.coef += q.data.coef;
                    p=p.next;
                    front=front.next;
                    q=q.next;
                }

            }else if (p.data.xexp>q.data.xexp){
                Node<TermX> temp = new Node<>(q.data, front.next);
                front.next=temp;
                front=front.next;
                q=q.next;
            }else if (p.data.xexp<q.data.xexp){
                p=p.next;
                front=front.next;
            }
        }
        while (q!=null){
            Node<TermX> temp = q;
            p.next=temp;
            p=p.next;
            q=q.next;
        }
    }

    @Override
    public String toString() {
        String str="该多项式为";
        Node<E> p =head.next;
        while (p.next!=null){
            TermX termX = (TermX) p.next.data;
            String symbol = termX.coef>0?"+":"";
            str+=p.data+symbol;
            p=p.next;
        }
        str+=p.data;
        return str;
    }
}